package com.vitas.coin.ui.fm

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.snap.base.util.BaseUtil
import com.snap.common.main.BaseFg
import com.snap.dialog.commonDialog
import com.vitas.coin.R
import com.vitas.coin.audio.Audio
import com.vitas.coin.data.event.DownloadEvent
import com.vitas.coin.databinding.FragmentHomeBinding
import com.vitas.coin.resp.CollectDaoResp
import com.vitas.coin.ui.adapter.LocalAdapter
import com.vitas.coin.util.PermissionsUtils
import com.vitas.coin.util.Utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LocalFrg : BaseFg() {
    lateinit var binding: FragmentHomeBinding
    var h = Handler(Looper.getMainLooper())
    var pageNumber = 0
    val pageSize = 50
    var adapter: LocalAdapter? = null
    val set = HashSet<Int>()
    val map = HashMap<String, Int>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHomeBinding.inflate(inflater, container, false)
        var bo = XXPermissions.isGranted(requireActivity(), Permission.MANAGE_EXTERNAL_STORAGE)
        binding.rvList.layoutManager =
            LinearLayoutManager(requireActivity(), RecyclerView.VERTICAL, false)
        initRefreshLayout()
        initObserve()

        if (bo) {
            getData(true)
        } else {
            binding.tvScan.visibility = View.VISIBLE
        }
        binding.tvScan.setOnClickListener({
            var bo = XXPermissions.isGranted(requireActivity(), Permission.MANAGE_EXTERNAL_STORAGE)
            if (bo) {
                getData(true)
            } else {
                showApplyPermissionPromptDialog()
            }
        })
        return binding.root
    }

    private fun initObserve() {
        BaseUtil.observer(this, DownloadEvent::class.java) {
            getData(true)
        }
    }

    private fun initRefreshLayout() {
        binding.mRefreshLayout.setRefreshHeader(ClassicsHeader(context))
        binding.mRefreshLayout.setRefreshFooter(ClassicsFooter(context))
        binding.mRefreshLayout.setEnableRefresh(true)
        binding.mRefreshLayout.setEnableLoadMore(true)
        binding.mRefreshLayout.setOnRefreshListener {
            pageNumber = 0
            getData(true)
        }
        binding.mRefreshLayout.setOnLoadMoreListener {
            pageNumber++
            getData(false)
        }
    }

    fun getData(refresh: Boolean) {
        GlobalScope.launch {
            if (refresh) {
                set.clear()
                var tmp = withContext(Dispatchers.IO) {
                    collectDaoResp.queryAll()
                }
                for (item in tmp) {
                    set.add(item.id)
                }

                map.clear()
                var list = Utils.getDownloaded()
                for (item in list) {
                    map.put(item.path, item.id)
                }
            }
            var list = Audio.loadAudio(requireActivity().application, pageNumber, pageSize)
            for (item in list) {
                if (map.contains(item.path)) {
                    item.id = map.get(item.path)!!
                }
                if (set.contains(item.addTime.toInt()) || set.contains(item.id)) {
                    item.setFavorite(1)
                } else {
                    item.setFavorite(0)
                }
            }
            h.post {
                if (adapter == null) {
                    adapter = LocalAdapter(requireActivity(), list)
                    binding.rvList.adapter = adapter
                } else {
                    if (refresh) {
                        adapter!!.resetList(list)
                        binding.mRefreshLayout.finishRefresh()
                    } else {
                        adapter!!.appendList(list)
                        binding.mRefreshLayout.finishLoadMore()
                    }
                }
                if (adapter!!.itemCount == 0) {
                    binding.tvScan.visibility = View.VISIBLE
                } else {
                    binding.tvScan.visibility = View.GONE
                }
            }
        }
    }

    private val collectDaoResp by lazy { CollectDaoResp }

    private fun showApplyPermissionPromptDialog() {
        commonDialog {
            setLayoutRes(R.layout.dialog_apply_permission_prompt) { view, dialog ->
                val tv_content: TextView = view.findViewById(R.id.tv_content)
                val permissionTips = "扫描本机铃声需要使用文件管理权限，请您授予该权限";
                tv_content.text = permissionTips
                view.findViewById<View>(R.id.ll_confirm).setOnClickListener { view ->
                    PermissionsUtils.startStoragePermission(requireActivity()) {
                        getData(true)
                    }
                    dismiss()
                }
            }
            setCanceledOnTouchOutside(false)
            setCanceledOnBackPressed(false)
        }.show(requireActivity())
    }
}
